import request from "@/services/interceptors";
import {
  enumToObject,
  ExerciseTypeEnum,
  QuestionTypeEnum,
  TopicType,
} from "@/utils/enums";
import {
  DragSortTable,
  ProCard,
  ProColumns,
  ProForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProTable,
} from "@ant-design/pro-components";
import { Alert, Button, message, Modal, Tabs } from "antd";
import { useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import ScoreEdit from "./ScoreEdit";
import { useAtomValue } from "jotai";
import { enumValuesAtom } from "@/store/enum";
import OperationDetail from "@/pages/topic/OperationTopic/OperationDetail";
import MyDrawer from "@/components/MyDrawer";
import ObjectDetail from "@/pages/topic/ObjectiveTopic/ObjectDetail";

interface TopicItem {
  id?: number;
  type?: TopicType;
  question?: string;
  score?: number;
  exerciseSteps?: any[];
  [key: string]: any;
}

const AddPaper = () => {
  const [topic, setTopic] = useState<TopicType>(TopicType.Objective);
  const actionRef = useRef<any>(null);
  const [topicList, setTopicList] = useState<TopicItem[]>([]);
  const { id: paperId } = useParams<{ id: string }>();
  const { courseList } = useAtomValue(enumValuesAtom);
  const formRef = useRef<ProFormInstance>(null);
  const navigate = useNavigate();

  // 可以添加一个 useEffect 来在组件加载时获取试卷数据
  useEffect(() => {
    if (!isNaN(+paperId)) {
      // 获取试卷详情
      fetchPaperDetail(+paperId);
    }
  }, [paperId]);

  // 获取试卷详情的函数
  const fetchPaperDetail = async (id: number) => {
    try {
      // 根据实际 API 调整
      const { data }: any = await request.sgks.paperDetailList({ id });
      if (data) {
        formRef.current.setFieldsValue({
          name: data.name,
          courseId: data.course.courseId,
        });
        // 设置试卷题目列表
        setTopicList([
          ...(data?.paperExercises ?? []).map((i) => ({
            ...i,
            score: i.exerciseSteps.reduce((prev, curr) => {
              return prev + curr.score;
            }, 0),
            id: i?.exerciseId,
            code: i?.exerciseCode,
            question: i?.exerciseInfo,
            type: TopicType.Operation,
          })),
          ...(data?.paperQuestions ?? []).map((i: any) => ({
            ...i,
            code: i?.questionCode,
            type: TopicType.Objective,
            id: i?.questionId,
            question: i?.questionStem,
          })),
        ]);
      }
    } catch (error) {
      console.error("获取试卷详情失败", error);
    }
  };

  const columns: ProColumns<TopicItem>[] = useMemo(() => {
    return topic === TopicType.Objective
      ? [
          {
            title: "题目编号",
            dataIndex: "questionCode",
            hideInSearch: true,
            width: 160,
            render: (text, record) => {
              return (
                <MyDrawer
                  title="客观题详情"
                  drawerContent={
                    <ObjectDetail questionId={record?.questionId} />
                  }
                >
                  <a type="link">{text}</a>
                </MyDrawer>
              );
            },
          },
          {
            title: "问题类型",
            dataIndex: "questionType",
            valueEnum: enumToObject(QuestionTypeEnum),
            width: "80px",
          },
          {
            title: "题干",
            dataIndex: "questionStem",
          },
          {
            title: "知识点",
            dataIndex: "labelsStr",
            width: "100px",
          },
          {
            title: "操作",
            dataIndex: "operation",
            render: (_, record) => {
              return !topicList.find(
                (i) => i.questionId === record.questionId
              ) ? (
                <ScoreEdit
                  editData={record}
                  onSuccess={(values) => {
                    setTopicList((prev) => {
                      const newList = [
                        ...prev,
                        {
                          ...record,
                          code: record?.questionCode,
                          score: values.score,
                          type: TopicType.Objective,
                          id: record?.questionId,
                          question: record?.questionStem,
                        },
                      ];
                      return newList;
                    });
                  }}
                  trigger={<Button type="primary">添加</Button>}
                />
              ) : (
                <Button
                  type="primary"
                  danger
                  onClick={() => {
                    setTopicList((prev) => {
                      return prev.filter(
                        (i) =>
                          !(
                            i.type === TopicType.Objective &&
                            i.id === record.questionId
                          )
                      );
                    });
                  }}
                >
                  移除
                </Button>
              );
            },
          },
        ]
      : [
          {
            title: "题目编号",
            dataIndex: "exerciseCode",
            hideInSearch: true,
            width: 160,
            render: (text, record) => {
              return (
                <MyDrawer
                  title="操作题详情"
                  drawerContent={
                    <OperationDetail exerciseId={+record?.exerciseId} />
                  }
                >
                  <a type="link">{text}</a>
                </MyDrawer>
              );
            },
          },
          {
            title: "问题类型",
            dataIndex: "exerciseType",
            valueEnum: enumToObject(ExerciseTypeEnum),
          },
          {
            title: "题干",
            dataIndex: "exerciseInfo",
          },
          {
            title: "知识点",
            dataIndex: "labels",
          },
          {
            title: "操作",
            dataIndex: "operation",
            render: (_, record) => {
              return !topicList.find(
                (i) => i.exerciseId === record.exerciseId
              ) ? (
                <ScoreEdit
                  editData={record}
                  onSuccess={(values) => {
                    const exerciseSteps = values.exerciseSteps;
                    const totalScore = exerciseSteps.reduce((prev, curr) => {
                      return prev + values[`score${curr?.exerciseStepId}`];
                    }, 0);

                    const nExerciseSteps = exerciseSteps.map((j) => {
                      return {
                        ...j,
                        score: values[`score${j?.exerciseStepId}`],
                      };
                    });
                    setTopicList((prev) => {
                      const newList = [
                        ...prev,
                        {
                          ...record,
                          code: record?.exerciseCode,
                          score: totalScore,
                          type: TopicType.Operation,
                          id: record?.exerciseId,
                          question: record?.exerciseInfo,
                          exerciseSteps: nExerciseSteps,
                        },
                      ];
                      return newList;
                    });
                  }}
                  trigger={<Button type="primary">添加</Button>}
                />
              ) : (
                <Button
                  size="small"
                  danger
                  type="primary"
                  onClick={() => {
                    setTopicList((prev) => {
                      return prev.filter(
                        (i) =>
                          !(
                            i.type === TopicType.Operation &&
                            i.id === record.exerciseId
                          )
                      );
                    });
                  }}
                >
                  移除
                </Button>
              );
            },
          },
        ];
  }, [topic, topicList]);

  const changeTabs = (e) => {
    setTopic(e as any);
    actionRef.current?.reload();
  };

  const topicItemColumns: ProColumns<TopicItem>[] = [
    {
      title: "序号",
      dataIndex: "sort",
      width: "80px",
      className: "drag-visible",
    },
    {
      title: "题目编号",
      dataIndex: "code",
      hideInSearch: true,
      width: 160,
      render: (text, record) => {
        return (
          <MyDrawer
            title="操作题详情"
            drawerContent={
              record.type === TopicType.Objective ? (
                <OperationDetail exerciseId={+record?.id} />
              ) : (
                <OperationDetail exerciseId={+record?.id} />
              )
            }
          >
            <a type="link">{text}</a>
          </MyDrawer>
        );
      },
    },
    {
      title: "题目类型",
      dataIndex: "type",
      width: "80px",
      valueEnum: {
        [TopicType.Objective]: "客观题",
        [TopicType.Operation]: "操作题",
      },
    },
    {
      title: "问题类型",
      dataIndex: "questionType",
      width: "80px",
      render: (_, record) => {
        return record.type === TopicType.Objective
          ? enumToObject(QuestionTypeEnum)[record.questionType]
          : enumToObject(ExerciseTypeEnum)[record.exerciseType];
      },
    },
    {
      title: "题干",
      dataIndex: "question",
    },
    {
      title: "分数",
      dataIndex: "score",
      width: "80px",
    },
    {
      title: "操作",
      width: "150px",
      render: (_, record) => {
        return [
          <ScoreEdit
            editData={record}
            trigger={
              <Button className="mr-[10px]" size="small" type="primary">
                编辑
              </Button>
            }
            onSuccess={(values) => {
              setTopicList((prev) => {
                return prev.map((i) => {
                  if (i.type === record.type && i.id === record.id) {
                    if (record.type === TopicType.Objective) {
                      return {
                        ...i,
                        score: values.score,
                      };
                    } else {
                      const exerciseSteps = i.exerciseSteps;
                      const total = exerciseSteps.reduce((prev, curr) => {
                        return prev + values[`score${curr?.exerciseStepId}`];
                      }, 0);

                      return {
                        ...i,
                        exerciseSteps: exerciseSteps.map((j) => {
                          return {
                            ...j,
                            score: values[`score${j?.exerciseStepId}`],
                          };
                        }),
                        score: total,
                      };
                    }
                  }
                  return i;
                });
              });
            }}
          />,
          <Button
            size="small"
            danger
            type="primary"
            onClick={() => {
              setTopicList((prev) => {
                return prev.filter(
                  (i) => !(i.type === record.type && i.id === record.id)
                );
              });
            }}
          >
            移除
          </Button>,
        ];
      },
    },
  ];
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);

  const handleDragSortEnd = (
    beforeIndex: number,
    afterIndex: number,
    newDataSource: any
  ) => {
    console.log("排序后的数据", newDataSource);
    setTopicList(newDataSource);
    message.success("修改列表排序成功");
  };

  const paperData = useMemo(() => {
    return topicList.map((i, index) => {
      return {
        ...i,
        sort: index + 1,
        rowKey: `${i.type}_${i.id}`,
      };
    });
  }, [topicList]);

  const totalScore = useMemo(() => {
    return paperData.reduce((prev, curr) => {
      return prev + (curr.score ?? 0);
    }, 0);
  }, [paperData]);

  console.log(paperData, "paperData");
  const handleSavePaper = async () => {
    formRef.current?.validateFields().then(async (values) => {
      if (paperData?.length === 0) {
        message.error("请添加题目");
        return;
      }
      if (paperData?.find((i) => !i.score)) {
        message.error(`请添加题目分数`);
        return;
      }
      if (totalScore !== 100) {
        message.error(`题目总分必须为100`);
        return;
      }
      Modal.confirm({
        title: "提示",
        content: "确定保存试卷吗？",
        onOk: async () => {
          const questions = paperData
            .filter((i) => i.type === TopicType.Objective)
            .map((j) => {
              return {
                questionId: j?.id,
                sort: j?.sort,
                score: j?.score,
              };
            });

          const exercises = [];
          paperData
            .filter((i) => i.type === TopicType.Operation)
            .forEach((i) => {
              i.exerciseSteps.forEach((j) => {
                exercises.push({
                  exerciseId: i?.id,
                  sort: i?.sort,
                  score: j?.score,
                  exerciseStepId: j?.exerciseStepId,
                });
              });
            });
          if (!isNaN(+paperId)) {
            console.log("修改试卷", values);
            await request.sgks.paperUpdateCreate({
              ...values,
              paperId: +paperId,
              paperQuestions: questions,
              paperExercises: exercises,
            });
          } else {
            await request.sgks.paperCreateCreate({
              ...values,
              paperQuestions: questions,
              paperExercises: exercises,
            });
          }
          message.success("保存成功");
          navigate("/paper/list");
        },
      });
    });
  };

  return (
    <>
      <Modal
        open={isModalOpen}
        footer={null}
        width={"80%"}
        onCancel={() => {
          setIsModalOpen(false);
        }}
      >
        <div className="pt-[20px]">
          <Alert message={`当前题目总分：${totalScore}`} type="info" />

          <Tabs
            defaultActiveKey={topic}
            activeKey={topic}
            onChange={changeTabs}
            items={[
              {
                label: "客观题",
                key: TopicType.Objective,
              },
              {
                label: "操作题",
                key: TopicType.Operation,
              },
            ]}
          />
          <ProTable<TopicItem>
            defaultSize="small"
            actionRef={actionRef}
            request={async (params) => {
              const nparams: any = {
                ...params,
                pageNo: params.current,
                pageSize: params.pageSize,
              };
              const res =
                topic === TopicType.Objective
                  ? await request.sgks.questionListCreate(nparams)
                  : await request.sgks.exerciseListCreate(nparams);

              return {
                data: res.data.records,
                total: res.data?.totalCount,
              };
            }}
            search={{
              labelWidth: "auto",
              span: 8,
            }}
            pagination={{
              pageSize: 10,
            }}
            toolBarRender={false}
            columns={columns}
          />
        </div>
      </Modal>
      <ProCard split="vertical">
        <div className="flex flex-col w-full mb-[20px]">
          <Alert message={`当前题目总分：${totalScore}`} type="info" />
          <div className="mt-[10px]">
            <ProForm
              formRef={formRef}
              layout="inline"
              submitter={{
                render: (props, doms) => [
                  <Button
                    ghost
                    type="primary"
                    onClick={() => {
                      setIsModalOpen(true);
                    }}
                  >
                    添加题目
                  </Button>,
                  <Button type="primary" onClick={handleSavePaper}>
                    保存试卷
                  </Button>,
                ],
              }}
            >
              <ProFormText
                name="name"
                label="试卷名称"
                placeholder="请输入试卷名称"
                rules={[
                  {
                    required: true,
                    message: "请输入试卷名称",
                  },
                ]}
              />
              <ProFormSelect
                required
                width={300}
                name="courseId"
                label="所属课程"
                rules={[{ required: true }]}
                options={courseList}
              />
            </ProForm>
          </div>
        </div>
        <DragSortTable<TopicItem>
          defaultSize="small"
          rowKey="rowKey"
          dragSortKey="sort"
          pagination={false}
          toolBarRender={false}
          search={false}
          columns={topicItemColumns}
          dataSource={paperData}
          onDragSortEnd={handleDragSortEnd}
        />
      </ProCard>
    </>
  );
};

export default AddPaper;
